//
//  LYDPopoverView.m

#import "FilterView.h"
#import "FilterTableViewCell.h"
#import "FilterSecondView.h"
#import "FilterSecondLevelModel.h"
#define kUIScreenHeight [UIScreen mainScreen].bounds.size.height
#define kUIScreenWidth [UIScreen mainScreen].bounds.size.width
@interface FilterView () <UITableViewDataSource,UITableViewDelegate,FilterSecondViewDelegate>
{
    NSMutableArray *firstLevelModelArray;
    NSMutableArray *currentArray;
    NSString *typeStr;
    
    NSUInteger parentIndex;
    
    BOOL clearAll;
}

@property (nonatomic, strong) UITableView *tableView;

//@property (nonatomic, assign) LYDPopoverViewDirection direction;

@property (nonatomic, strong) UIView *theContentView;

@property (nonatomic, strong) UIButton *alphaBtn;

@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UIButton *restartBtn;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *confirmBtn;
@property (nonatomic, strong) UILabel *topLineLabel;
@property (nonatomic, assign) CGSize size;

@end

@implementation FilterView

#pragma mark - settet&getter


#pragma mark - 初始化类方法

+ (instancetype)FilterViewWithSize:(CGSize)size
{
    
    FilterView *popView = [[self alloc] init];

  
    popView.size =size;
    return popView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}
-(void)setSelectedSearchBeansArray:(NSMutableArray *)selectedSearchBeansArray{
   
    if (selectedSearchBeansArray.count>0) {
        [currentArray removeAllObjects];
//         NSLog(@" selectedSearchBeansArray>>>>>==%@",selectedSearchBeansArray);
        for (NSDictionary* dicc in selectedSearchBeansArray )
        {
            NSArray *imgArray=dicc[@"items"];
            for (NSDictionary *dic in imgArray)
            {
                FilterSecondLevelModel *secondLevelModel=[FilterSecondLevelModel dataModelWithDict:dic];
                [currentArray addObject:secondLevelModel];
                
            }

            
            
        }
        [_tableView reloadData];

    }
}
-(void)requestFilterList
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
//      NSLog(@" self.typeStr====$=%@", self.typeStr);
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:self.typeStr forKey:@"filterType"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self];
   
    [HttpRequest requestData:@"Common/AdvancedFilterList" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self];
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
              NSLog(@"arrr#######====%@",arrr);
                for (NSDictionary* dicc in arrr )
                {
                    FilterFirstLevelModel *firstLevelModel=[FilterFirstLevelModel dataModelWithDict:dicc];
                    [firstLevelModelArray addObject:firstLevelModel];
                    
                    FilterSecondLevelModel *secondModel=[FilterSecondLevelModel dataModelWithDict:dicc[@"current"]];
                    [currentArray addObject:secondModel];
                }

                [_tableView reloadData];
                
            }
            else{
                [Global hideProgressHUDInternal:self];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self];
            
            [Global showTextHudSub:severDataDict.resultStr view:self];
        }
        
    }];
    
}

- (void)setup
{
    clearAll=NO;
    firstLevelModelArray=[NSMutableArray array];
    currentArray=[NSMutableArray array];
    _alphaBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_alphaBtn addTarget:self action:@selector(alphaBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_alphaBtn setBackgroundColor: [UIColor blackColor]];
    _alphaBtn.alpha=0.6;
    [self addSubview:_alphaBtn];
    
    _theContentView=[[UIView alloc] init];
    _theContentView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_theContentView];
    
    _cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_cancelBtn setTitleColor:[UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1.0] forState:UIControlStateNormal];
    [_cancelBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [_cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [_theContentView addSubview:_cancelBtn];
    
   _restartBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_restartBtn setTitleColor:[UIColor colorWithRed:90.0f/255.0f green:130.0f/255.0f blue:26.0f/255.0f alpha:1.0] forState:UIControlStateNormal];
    [_restartBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
     [_restartBtn addTarget:self action:@selector(restartBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_restartBtn setTitle:@"重置" forState:UIControlStateNormal];
    [_theContentView addSubview:_restartBtn];
    
    _titleLabel=[[UILabel alloc] init];
    _titleLabel.text=@"筛选";
    _titleLabel.textColor=[UIColor blackColor];
    [_titleLabel setFont:[UIFont systemFontOfSize:17]];
    [_theContentView addSubview:_titleLabel];
    
    _topLineLabel=[[UILabel alloc] init];
    [_topLineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [_theContentView addSubview:_topLineLabel];
    
   _confirmBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_confirmBtn setBackgroundColor:[UIColor colorWithRed:90.0f/255.0f green:130.0f/255.0f blue:26.0f/255.0f alpha:1.0]];
    [_confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_confirmBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [_confirmBtn addTarget:self action:@selector(confirmBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_theContentView addSubview:_confirmBtn];

    
    _tableView = [[UITableView alloc] init];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.bounces = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_theContentView addSubview:_tableView];
    
    
}
-(void)cancelBtnClick
{
//    NSMutableArray *searchBeans=[NSMutableArray array];
//    if ([self.delegate respondsToSelector:@selector(confirmFilter:)]) {
//        [self.delegate confirmFilter: searchBeans];
//    }
    if ([self.delegate respondsToSelector:@selector(cancelPop)]) {
        [self.delegate cancelPop];
    }
    [self dismiss];

}
-(void)restartBtnClick
{
    clearAll=YES;
    [firstLevelModelArray removeAllObjects];
    [currentArray removeAllObjects];
    [self requestFilterList];
}
-(void)confirmBtnClick
{
    NSMutableArray *searchBeans=[NSMutableArray array];
    for (int i=0; i<firstLevelModelArray.count; i++) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        FilterFirstLevelModel *firstModel=firstLevelModelArray[i];
        [dic setValue:firstModel.typeCode forKey:@"typeCode"];
        [dic setValue:firstModel.isSingle forKey:@"isSingle"];
        [dic setValue:firstModel.typeName forKey:@"typeName"];
        [dic setValue:firstModel.dataType forKey:@"dataType"];
        
        NSMutableArray *itemsArray=[NSMutableArray array];
        FilterSecondLevelModel *secondModel=currentArray[i];
        NSMutableDictionary *itemsDic= [NSMutableDictionary dictionary];
        [itemsDic setObject:secondModel.itemName forKey:@"itemName"];
        [itemsDic setObject:secondModel.itemValue forKey:@"itemValue"];
        [itemsDic setObject:secondModel.minValue forKey:@"minValue"];
        [itemsDic setObject:secondModel.maxValue forKey:@"maxValue"];
        [itemsDic setObject:secondModel.isCustom forKey:@"isCustom"];
        [itemsDic setObject:secondModel.isRange forKey:@"isRange"];
        [itemsArray addObject:itemsDic];
        [dic setObject:itemsArray forKey:@"items"];
        [searchBeans addObject:dic];
        
//        NSLog(@"itemname=====%@",secondModel.itemName);
    }
//     NSLog(@"searchBeans>>>>>==%@",searchBeans);
    if (clearAll) {
        [searchBeans removeAllObjects];
    }
    if ([self.delegate respondsToSelector:@selector(confirmFilter:)]) {
        [self.delegate confirmFilter: searchBeans];
    }
    [self dismiss];
    
}
-(void)alphaBtnClick
{
    [self dismiss];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [_alphaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.top.equalTo(self.mas_top);
        make.bottom.equalTo(self.mas_bottom);
        make.width.equalTo(@45);
    }];
    [_theContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_alphaBtn.mas_right);
            make.top.equalTo(self.mas_top);
            make.bottom.equalTo(self.mas_bottom);
            make.right.equalTo(self.mas_right);
        }];
  
    [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_theContentView.mas_left).with.offset(10);
        make.top.equalTo(_theContentView.mas_top).with.offset(25);
        make.height.equalTo(@30);
        make.width.equalTo(@40);
    }];
    [_restartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_theContentView.mas_right).with.offset(-10);
        make.top.equalTo(_theContentView.mas_top).with.offset(25);
        make.height.equalTo(@30);
        make.width.equalTo(@40);
    }];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_theContentView.mas_centerX);
        make.top.equalTo(_theContentView.mas_top).with.offset(25);
        make.height.equalTo(@30);
        make.width.equalTo(@40);
    }];
    
    [_topLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_theContentView.mas_left).with.offset(0);
        make.top.equalTo(_theContentView.mas_top).with.offset(63);
        make.height.equalTo(@0.5);
        make.right.equalTo(_theContentView.mas_right).with.offset(0);
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_theContentView.mas_left);
        make.top.equalTo(_topLineLabel.mas_bottom);
        make.bottom.equalTo(_theContentView.mas_bottom).with.offset(-45);
        make.right.equalTo(_theContentView.mas_right);
    }];
    [_confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_theContentView.mas_left);
        make.bottom.equalTo(_theContentView.mas_bottom);
        make.height.equalTo(@45);
        make.right.equalTo(_theContentView.mas_right);
    }];

    
    
    
}

- (void)show
{
    // 获得主窗口
     UIWindow *window = [UIApplication sharedApplication].keyWindow;

    self.frame= CGRectMake(kUIScreenWidth, 0, kUIScreenWidth, kUIScreenHeight);
    
    [window addSubview:self];
  
    [UIView animateWithDuration:0.6 animations:^{
      self.frame= CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight);
    }];

    [self requestFilterList];
}

- (void)dismiss
{
    [self removeFromSuperview];
    
}
#pragma mark - tableView代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 53;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return firstLevelModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString * const  CellIdentifier = @"FilterTableViewCellIdentifier";
        FilterTableViewCell *cell=( FilterTableViewCell *)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FilterTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
    cell.model=firstLevelModelArray[indexPath.row];
    
    FilterSecondLevelModel *secondModel=currentArray[indexPath.row];
    cell.itemNameLabel.text=secondModel.itemName;
       return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    parentIndex=indexPath.row;
    
    FilterFirstLevelModel *firstModel=firstLevelModelArray[indexPath.row];
    FilterSecondLevelModel *secondModel=currentArray[indexPath.row];
    FilterSecondView *secondView=[[FilterSecondView alloc] init:firstModel.secondModelArray secondLevelModel:secondModel title:firstModel.typeName isLikeSearch:firstModel.isLikeSearch];
    secondView.frame=self.frame;
    secondView.delegate=self;
    secondView.typeStr=self.typeStr;
    
    secondView.parentIndex=[NSString stringWithFormat:@"%ld",parentIndex];

  [self addSubview:secondView];
    
}
#pragma mark FilterSecondViewDelegate
- (void)FilterSecondView:(FilterSecondLevelModel *)secondLevelModel cellIndex:(NSInteger)cellIndex
{
    [currentArray replaceObjectAtIndex:parentIndex withObject:secondLevelModel];
    [_tableView reloadData];
}

@end
